using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using IMServer.Services;

namespace IMServer.Models
{
    public class Group
    {
        [BsonId]
        public ObjectId Id { get; set; }

        [BsonElement("groupId")]
        public string GroupId { get; set; } = null!;

        [BsonElement("groupName")]
        public string GroupName { get; set; } = null!;

        [BsonElement("avatar")]
        public string Avatar { get; set; } = "https://im-net.oss-cn-wuhan-lr.aliyuncs.com/group-profile-avatar.jpg";

        [BsonElement("creator")]
        public string Creator { get; set; } = null!;  // 群主
        
        [BsonElement("adminId")]
        public string[] AdminId { get; set; } = [];

        [BsonElement("members")]
        public string[] Members { get; set; } = [];

        public void GenerateGroupId()
        {
            if (GroupId == null)
            {
                string timestamp = DateTime.UtcNow.Ticks.ToString().Substring(8, 6);
                string randomNum = new Random().Next(10000, 100000).ToString().Substring(1, 4);
                this.GroupId = timestamp + randomNum;
            }
        }

        // 获取群组成员列表
        public string[] GetMembers()
        {
            return Members ?? [];
        }

        // 检查用户是否是群组成员
        public bool IsMember(string userId)
        {
            return Members?.Contains(userId) ?? false;
        }

        // 检查用户是否是管理员
        public bool IsAdmin(string userId)
        {
            return AdminId.Contains(userId);
        }

        // 生成初始群组名称
        public async Task<bool> GenerateGroupName()
        {
            try 
            {
                var userService = UserDbService.Instance;
                var memberNames = new List<string>();
                
                // 获取前三个成员的用户名
                for (int i = 0; i < Math.Min(3, Members.Length); i++)
                {
                    var user = await userService.GetUserByUserIdAsync(Members[i]);
                    if (user != null)
                    {
                        memberNames.Add(user.UserName);
                    }
                }

                // 如果有超过3个成员，添加"等"字
                string suffix = Members.Length > 3 ? "等" : "";
                
                // 组合成群组名称：用户1、用户2、用户3等
                GroupName =  string.Join("、", memberNames) + suffix;
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"生成群组名称失败: {ex.Message}");
                return false;
            }
        }
    }
}
